import Toast, { hideToast } from 'tdesign-miniprogram/toast'
const app = getApp()

Page({
  onShow() {
    wx.reportAnalytics('enter_my_programmatically', {})
    this.getTabBar().setData({active: 'my'})
  },
  onShareAppMessage() {
    return {
      title: '首页',
      path: 'page/home/index'
    }
  },
  onShareTimeline() {
    '首页'
  },

  data: {
    loading: {loading: false},
    theme: 'light',
    user: null,
    onGlobalUserChange: null,
    visible: {
      del: false
    }
  },

  onLoad() {
    this.data.onGlobalUserChange = this.onGlobalUserChange.bind(this)
    app.watch('user', this.data.onGlobalUserChange)
    this.setData({
      theme: wx.getSystemInfoSync().theme || 'light',
      user: app.globalData.user,
    })

    if (wx.onThemeChange) {
      wx.onThemeChange(({theme}) => {
        this.setData({theme})
      })
    }
  },
  onUnload() {
    app.unWatch('user', this.data.onGlobalUserChange)
  },
  onGlobalUserChange(val, pre) {
    this.setData({
      user: val,
    })
  },
  toast(option) {
    Toast({
      context: this,
      selector: '#t-toast',
      ...option,
    });
  },
  toastHide() {
    hideToast({
      context: this,
      selector: '#t-toast',
    });
  },
  go2label(e) {
    wx.navigateTo({
      url: '/packageMy/pages/label/index',
      events: {
        submit: (labels) => {
          const { user } = this.data
          if (user.labels.toString() === labels.toString()) return
          this.updateUser({labels})
        },
      },
      success: (res) => {
        res.eventChannel.emit('init', { value: this.data.user.labels })
      },
    })
  },
  go2desc(e) {
    wx.navigateTo({
      url: '/packageMy/pages/desc/index',
      events: {
        submit: (desc) => {
          const { user } = this.data
          if (user.desc === desc) return
          this.updateUser({desc})
        },
      },
      success: (res) => {
        res.eventChannel.emit('init', { value: this.data.user.desc })
      },
    })
  },
  updateUser(data) {
    this.toast({
      theme: 'loading',
      direction: 'column',
      duration: 10000,
    })
    wx.cloud.callFunction({
      name: 'user',
      data: {
        action: 'update',
        data: {
          _id: this.data.user._id,
          ...data,
        }
      } 
    })
    .then(() => {
      app.globalData.user =  {...app.globalData.user, ...data}
    })
    .catch(() => this.toast({
      theme: 'fail',
      direction: 'column',
      message: '更新失败'
    }))
    .finally(() => this.toastHide())
  },
  getUserInfo(e) {
    app.registerUser(e.detail.userInfo)
  },
})
